package com.example.interceptors;

import com.example.utils.JWTUtil;
import com.example.utils.ThreadLocalUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Description TODO
 * @Author fantasy
 * @Date 2024/6/27 21:53
 **/

@Component
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 拦截器
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     * @Description 由于每次请求都会在请求头携带token，所以拦截器会先获取token，然后解析token，然后把用户信息保存到ThreadLocal中
     * 所以，在请求处理之前可以把token解析的用户信息保存到ThreadLocal中，请求处理之后，把ThreadLocal中的用户信息删除
     * @Author fantasy
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token == null) {
            response.setStatus(401);
            return false;
        }
        try {
//            解析JWT token
            Map<String, Object> map = JWTUtil.verifyJwt(token);
//            把用户信息保存到ThreadLocal
            ThreadLocalUtil.set(map);
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        请求处理之后，把ThreadLocal中的用户信息删除
        ThreadLocalUtil.remove();
    }
}
